package com.qfedu.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class ConnectionUtils {
    private ThreadLocal<Connection> threadlocal = new ThreadLocal<Connection>();
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Connection getThreadConnection() {
        Connection connection = threadlocal.get();

        if (connection == null) {//没有连接
            // 需要从数据库中获取一个连接对象
            try {
                connection = dataSource.getConnection();
                threadlocal.set(connection);
                return connection;


            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
        /**
         * 将当前线程和连接对象解绑
         */
        public void removeConnection () {
            threadlocal.remove();
        }
    }
